package com.example.pythondemo.utils;

import com.example.pythondemo.model.FileNum;

import java.io.*;
import java.util.List;

public class FileKit {

    public static boolean write(List<String> lines, String filePath, String charsetName, FileNum fileNum){
        File file = new File(filePath);
        String path = filePath.substring(0, filePath.lastIndexOf('/'));
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        try {
            OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file),charsetName);
            BufferedWriter bw = new BufferedWriter(os);
            if (lines == null || lines.size() == 0){
                bw.write("");
            }else {
                for (int i = 0; i < lines.size(); i++) {
                    if (i >= lines.size()-1){

                        bw.write(lines.get(i).split("斗罗大陆II")[0]);
                    }else {
                        if(i == 0 || i == 1){
                            continue;
                        }
                        bw.write(lines.get(i)+"\n");
                    }
                }
            }
            bw.flush();
            fileNum.addDown();
            return true;
        } catch (Exception e) {
            fileNum.addFalse();
            return false;
        }
    }

    public static boolean write(List<String> lines, String filePath, String charsetName){
        System.out.println("开始写入文件：" + filePath);
        File file = new File(filePath);
        String path = filePath.substring(0, filePath.lastIndexOf('/'));
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        try {
            OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file),charsetName);
            BufferedWriter bw = new BufferedWriter(os);
            if (lines == null || lines.size() == 0){
                bw.write("");
            }else {
                for (int i = 0; i < lines.size(); i++) {
                    if (i >= lines.size()-1){//太古星辰决

                        bw.write(lines.get(i).split("斗罗大陆II")[0]);
                    }else {
                        if(i == 0 || i == 1){
                            continue;
                        }
                        bw.write(lines.get(i)+"\n");
                    }
                }
            }
            bw.flush();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
